import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios';
import { message } from 'antd';
import AdminConfig from '../config'

axios.defaults.baseURL = AdminConfig.API_URL
axios.defaults.withCredentials = true

// 添加请求拦截器
axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        return config;
    },
    (error: AxiosError) => Promise.reject(error),
);

axios.interceptors.response.use(
    (response: AxiosResponse) => {
        if (!response.data) {
            return Promise.resolve(response);
        }
        // 请求成功
        if (response.data.code === AdminConfig.SUCCESS_CODE) {
            return response.data.data as any;
        }

        // 请求成功，状态不为成功时
        message.error(response.data.msg);

        return Promise.reject(response.data);
    },
    (error: AxiosError) => {
        message.error(error.message);

        return Promise.reject(error);
    },
);

// 统一发起请求的函数
export const Get = (url: string, params?: unknown): Promise<any> => {
    return axios.request({
        method: 'get',
        url,
        params
    })
}
export const Post = (url: string, params: unknown): Promise<any> => {
    return axios.request({
        method: 'post',
        url,
        params
    })
}
export const PostJson = (url: string, data: unknown): Promise<any> => {
    return axios.request({
        method: 'post',
        url,
        data
    })
}